package cn.elwy.rcp.ui.util;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.internal.win32.OS;
import org.eclipse.swt.internal.win32.TCHAR;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.wb.swt.SWTResourceManager;

/**
 * 窗口居中、清除背景等功能
 * 
 * @author huangsq
 * @version 1.0, 2013-11-20
 * @since 1.0, 2013-11-20
 */
@SuppressWarnings("restriction")
public class ShellUtil {

  private ShellUtil() {
  }

  /**
   * 相对屏幕居中
   * 
   * @param control 当前控件
   */
  public static void shellCentre(Control control) {
    Display display = Display.getCurrent();
    if (display == null) {
      display = Display.getDefault();
    }
    int width = display.getBounds().width;
    int height = display.getBounds().height;
    control.setLocation(width / 2 - control.getSize().x / 2, height / 2 - control.getSize().y / 2);
  }

  /**
   * 相对控件或父窗口居中
   * 
   * @param parent 父控件
   * @param control 当前控件
   */
  public static void shellCentre(Control parent, Control control) {
    if (parent == null) {
      shellCentre(control);
      return;
    }
    Rectangle parentBounds = parent.getBounds();
    Rectangle shellBounds = control.getBounds();
    int x = parentBounds.x + (parentBounds.width - shellBounds.width) / 2;
    int y = parentBounds.y + (parentBounds.height - shellBounds.height) / 2;

    control.setLocation(x, y);
  }

  /**
   * 清除当前控件背景
   * 
   * @param control 当前控件
   */
  public static void clearBackground(Control control) {
    control.setBackground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
    OS.SetWindowLong(control.handle, OS.GWL_EXSTYLE, OS.GetWindowLong(control.handle, OS.GWL_EXSTYLE) ^ 0x80000);
    TCHAR lpLibFileName = new TCHAR(0, "User32.dll", true);
    int hInst = (int) OS.LoadLibrary(lpLibFileName);
    if (hInst != 0) {
      String name = "SetLayeredWindowAttributes\0";
      byte[] lpProcName = new byte[name.length()];
      for (int i = 0; i < lpProcName.length; i++) {
        lpProcName[i] = (byte) name.charAt(i);
      }
      int fun = (int) OS.GetProcAddress(hInst, lpProcName);
      if (fun != 0) {
        OS.CallWindowProc(fun, control.handle, 0, 50, 1);
      }
      OS.FreeLibrary(hInst);
    }
  }

}
